package com.system.healthproject.model.sickuser.service.imp;

import com.system.healthproject.mapper.AppCodeMapper;
import com.system.healthproject.mapper.PatientMapper;
import com.system.healthproject.mapper.RoleMapper;
import com.system.healthproject.model.sickuser.service.UserAppCodeService;
import com.system.healthproject.pojo.AppCode;
import com.system.healthproject.pojo.Patient;
import com.system.healthproject.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Service
public class UserAppCodeServiceImp implements UserAppCodeService {

    @Autowired
    AppCodeMapper appCodeMapper;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    RoleMapper roleMapper;

    @Transactional
    @Override
    public boolean useCode(Integer appCodeId, Integer loginId) {
        AppCode appCode = appCodeMapper.selectByPrimaryKey(appCodeId);
        Integer appcodeRemainder = appCode.getAppcodeRemainder();//获取二维码剩余数量
        if(appcodeRemainder>0){
            Integer membershiptime = appCode.getMembershiptime();
            Patient patient = patientMapper.selectByLoginId(loginId);
            Integer membervalidity = patient.getMembervalidity();
            if(membervalidity==null){
                membervalidity=0;
            }
            int membervalidity1 = membervalidity + membershiptime;//计算出新的会员剩余天数
            patient.setMembervalidity(membervalidity1);
            Date date=new   Date();//取时间
            Calendar calendar   =   new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE,membervalidity1);//把日期往后增加一天.整数往后推,负数往前移动
            date=calendar.getTime();
            patient.setMemberexpirationtime(date);//重新设置会员的过期时间
            patientMapper.updateByPrimaryKey(patient);
            List<Role> roles = roleMapper.selectRoleByLoginId(loginId);
            boolean isRole=false;
            for (Role role : roles) {
                if(role.getRoleName().equals("memberPatient")){
                    isRole=true;
                }
            }
            if(!isRole){
                roleMapper.userChangeRole(loginId,5);
            }
            int i = appCodeMapper.addUserCode(loginId, appCodeId,new Date());
            return i==1;
        }
        return false;
    }
}
